package com.xb.cloud.merchantapi.product.service.impl;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xb.cloud.common.constant.DbConstants;
import com.xb.cloud.common.util.KeyUtils;
import com.xb.cloud.gateway.client.ReturnCodes;
import com.xb.cloud.gateway.client.ReturnUtils;
import com.xb.cloud.gateway.client.RtnCodes;
import com.xb.cloud.gateway.client.RtnInfo;
import com.xb.cloud.merchantapi.product.service.ProductPublishApiService;
import com.xb.cloud.order.service.client.ProductStockService;
import com.xb.cloud.product.merchant.service.client.EndMerchantUserService;
import com.xb.cloud.product.merchant.service.client.ProductMongoService;
import com.xb.cloud.product.merchant.service.client.ProductPublishService;
import com.xb.cloud.product.merchant.service.client.bo.EndMerchantUserBo;
import com.xb.cloud.product.merchant.service.client.bo.ProductMongoBo;
import com.xb.cloud.product.merchant.service.client.bo.ProductShopSeriesMongoBo;
import com.xb.cloud.product.merchant.service.client.bo.ProductTemplateBo;
import com.xb.cloud.product.merchant.service.client.bo.PublishableProductSerialAttrCombBo;
import com.xb.cloud.product.merchant.service.client.input.bo.ProductSkuInputBo;
import com.xb.cloud.product.merchant.service.client.input.bo.ProductSkuPicInputBo;
import com.xb.cloud.service.client.ServiceReturnInfo;
import com.xb.cloud.service.client.ServiceReturnUtils;

/**
 * 
 * @Description:商家发布商品，获取类目数据服务
 * @author: 鲜备科技
 * 
 * @Copyright: 2017 www.xianbeitech.com Inc. All rights reserved.
 *
 */
@Service
public class ProductPublishApiServiceImpl implements ProductPublishApiService {

	@Autowired
	private ProductPublishService productPublishService;

	@Autowired
	private ProductMongoService productMongoService;

	@Autowired
	private ProductStockService productStockService;

	@Resource
	private EndMerchantUserService endMerchantUserService;

	/**
	 * 根据类目id获取该类目节点下的所有的待发布商品列表; [分页]
	 */
	@Override
	public RtnInfo getPublishableProductSummaryBoListByCategoryId(Long categoryId, Long currentMerchantUserId,
			Integer pageNum, Integer pageSize) {
		EndMerchantUserBo endMerchantUserBo = null;
		// 获取当前merchantId对应的商家用户
		ServiceReturnInfo merchantReturnInfo = endMerchantUserService.getEndMerchantUserById(currentMerchantUserId);
		if (ServiceReturnUtils.isSuccess(merchantReturnInfo)) {
			if (merchantReturnInfo.getData() == null) {
				return ReturnUtils.error(ReturnCodes.MERCHANT_NOT_EXIST);
			} else {
				endMerchantUserBo = (EndMerchantUserBo) merchantReturnInfo.getData();
			}
		} else {
			return ReturnUtils.error(ReturnCodes.SYSTEM_EXCEPTION);
		}

		Long companyId = endMerchantUserBo.getCompanyId();
		Long shopId = endMerchantUserBo.getShopId();
		// 获取数据
		ServiceReturnInfo returnInfo = productPublishService.getPublishableProductSummaryBoListByCategoryId(categoryId,
				companyId, shopId, pageNum, pageSize);

		if (ServiceReturnUtils.isSuccess(returnInfo)) {
			return ReturnUtils.success(returnInfo.getData());
		} else {
			return ReturnUtils.error(ReturnCodes.SYSTEM_EXCEPTION);
		}

	}
	/**
	 * 根据类目id获取该类目节点下的所有的待发布商品列表; [分页] merchant level 
	 */
	@Override
	public RtnInfo getPublishableProductSummaryBoListMerchantLevelByCategoryId(Long categoryId,
			Long currentMerchantUserId, Integer pageNum, Integer pageSize) {
		EndMerchantUserBo endMerchantUserBo = null;
		// 获取当前merchantId对应的商家用户
		ServiceReturnInfo merchantReturnInfo = endMerchantUserService.getEndMerchantUserById(currentMerchantUserId);
		if (ServiceReturnUtils.isSuccess(merchantReturnInfo)) {
			if (merchantReturnInfo.getData() == null) {
				return ReturnUtils.error(ReturnCodes.MERCHANT_NOT_EXIST);
			} else {
				endMerchantUserBo = (EndMerchantUserBo) merchantReturnInfo.getData();
			}
		} else {
			return ReturnUtils.error(ReturnCodes.SYSTEM_EXCEPTION);
		}

		//Long merchantId = endMerchantUserBo.getMerchantId();
		Long shopId = endMerchantUserBo.getShopId();
		// 获取数据
		ServiceReturnInfo returnInfo = productPublishService.getPublishableProductSummaryBoListMerchantLevelByCategoryId(categoryId,
				endMerchantUserBo.getMerchantId(), shopId, pageNum, pageSize);

		if (ServiceReturnUtils.isSuccess(returnInfo)) {
			return ReturnUtils.success(returnInfo.getData());
		} else {
			return ReturnUtils.error(ReturnCodes.SYSTEM_EXCEPTION);
		}

	}

	/**
	 * 根据系列品虚品id,获取当前系列品下，该店铺未发布的系列组合的列表 数据
	 * 
	 * @return
	 */
	@Override
	public RtnInfo getPublishableProductSerialAttrCombBoByProductId(Long productId, Long endMerchantUserId) {
		RtnInfo rtnInfo = new RtnInfo();
		PublishableProductSerialAttrCombBo publishableSerialAttrCombBo = new PublishableProductSerialAttrCombBo();

		EndMerchantUserBo endMerchantUserBo = null;
		// 获取当前merchantId对应的商家用户
		ServiceReturnInfo merchantReturnInfo = endMerchantUserService.getEndMerchantUserById(endMerchantUserId);
		if (ServiceReturnUtils.isSuccess(merchantReturnInfo)) {
			if (merchantReturnInfo.getData() == null) {
				return ReturnUtils.error(ReturnCodes.MERCHANT_NOT_EXIST);
			} else {
				endMerchantUserBo = (EndMerchantUserBo) merchantReturnInfo.getData();
			}
		} else {
			return ReturnUtils.error(ReturnCodes.SYSTEM_EXCEPTION);
		}

		// 获取Mongo数据
		ServiceReturnInfo productMongoBoReturnInfo = productMongoService.findById(productId);
		ProductMongoBo productMongoBo = null;
		if (ServiceReturnUtils.isSuccess(productMongoBoReturnInfo)) {
			if (productMongoBoReturnInfo.getData() == null) {
				// 产品id对应的mongo数据不存在.
				return ReturnUtils.error(ReturnCodes.PRODUCT_MONGO_NOT_EXIST);
			} else {
				productMongoBo = (ProductMongoBo) productMongoBoReturnInfo.getData();
			}
		} else {
			return ReturnUtils.error(ReturnCodes.SYSTEM_EXCEPTION);
		}

		// 获取Mongo系列品组合数据
		ServiceReturnInfo seriesMongoBoReturnInfo = productMongoService
				.findByProductShopId(KeyUtils.generateProductShopKey(productId, endMerchantUserBo.getShopId()));
		ProductShopSeriesMongoBo productShopSeriesMongoBo = null;
		if (ServiceReturnUtils.isSuccess(seriesMongoBoReturnInfo)) {
			if (seriesMongoBoReturnInfo.getData() == null) {
				// 产品id对应的mongo数据不存在.
				productShopSeriesMongoBo=new ProductShopSeriesMongoBo();
			} else {
				productShopSeriesMongoBo = (ProductShopSeriesMongoBo) seriesMongoBoReturnInfo.getData();
			}
		} else {
			return ReturnUtils.error(ReturnCodes.SYSTEM_EXCEPTION);
		}
		// 设置系列属性
		publishableSerialAttrCombBo.setSeriesAttrs(productMongoBo.getSeriesAttrs());
		publishableSerialAttrCombBo.setSeriesAttributeCombProductIdMap(productMongoBo.getSeriesAttributeCombProductIdMap());

		// 该店铺已经发布过当前的Sku.
		publishableSerialAttrCombBo.getSeriesAttributeCombProductIdList()
				.addAll(productShopSeriesMongoBo.getSeriesAttributeCombSkuIdMap().keySet());

		rtnInfo.setData(publishableSerialAttrCombBo);
		rtnInfo.setRtnCode(RtnCodes.SUCCESS);
		return rtnInfo;
	}

	/**
	 * 根据商品id,获取待发布商品的模板数据
	 * 
	 * productType : productId1对应的类型 productId1 : 如果是系列品,此id为虚品id ；
	 * 如果是单品，此id为单品id ; productId2 : 如果是系列品,此id为子品id ； 如果是单品，此id为空 ;
	 * 
	 * @return
	 */
	@Override
	public RtnInfo getProductTemplateBoByProductId(Byte productType, Long productId1, Long productId2,
			String seriesAttributeCombProductId) {
		RtnInfo rtnInfo = new RtnInfo();

		boolean isLegalSerial = (productType != null
				&& productType.intValue() == (DbConstants.PRODUCT_TYPE_SERIAS_VIRTUAL) && productId1 != null
				&& productId2 != null);
		boolean isLegalSingle = (productType != null && productType.intValue() == (DbConstants.PRODUCT_TYPE_SINGLE)
				&& productId1 != null);
		if (!(isLegalSerial || isLegalSingle)) {
			// 验证系列品参数.
			// 验证单品参数.
			return ReturnUtils.error(ReturnCodes.PARAM_INVALID);
		}

		ProductTemplateBo productTemplateBo = null;
		if (productType.byteValue() == DbConstants.PRODUCT_TYPE_SERIAS_VIRTUAL) {
			// 系列品使用第二个productId,获取当前数据
			ServiceReturnInfo productTemplReturnInfo = productPublishService
					.getProductTemplateBoByProductId(productId2);
			productTemplateBo = (ProductTemplateBo) productTemplReturnInfo.getData();
		} else {
			// 单品数据
			ServiceReturnInfo productTemplReturnInfo = productPublishService
					.getProductTemplateBoByProductId(productId1);
			productTemplateBo = (ProductTemplateBo) productTemplReturnInfo.getData();
		}

		if (productTemplateBo == null) {
			// 返回产品id对应的模板不存在.
			return ReturnUtils.error(ReturnCodes.PRODUCT_TEMPLATE_NOT_EXIST);
		}
		// 获取Mongo数据
		
		ServiceReturnInfo productMongoBoReturnInfo = productMongoService.findById(productId1);
		ProductMongoBo productMongoBo = null;
		if (ServiceReturnUtils.isSuccess(productMongoBoReturnInfo)) {
			if (productMongoBoReturnInfo.getData() == null) {
				// 产品id对应的mongo数据不存在.
				return ReturnUtils.error(ReturnCodes.PRODUCT_MONGO_NOT_EXIST);
			} else {
				productMongoBo = (ProductMongoBo) productMongoBoReturnInfo.getData();
			}
		} else {
			return ReturnUtils.error(ReturnCodes.SYSTEM_EXCEPTION);
		}
		
		productTemplateBo.setBaseAttrs(productMongoBo.getBaseAttrs());
		productTemplateBo.setSeriesAttrs(productMongoBo.getSeriesAttrs());
		// 当前系列品对应系列属性组合生成的key (1-2_1-1)
		productTemplateBo.setSeriesAttributeCombProductId(seriesAttributeCombProductId);
		

		rtnInfo.setData(productTemplateBo);
		rtnInfo.setRtnCode(RtnCodes.SUCCESS);
		return rtnInfo;
	}

	/**
	 * 发布sku分两个库，
	 * 
	 * @param endMerchantUserBo
	 * @param productId1
	 * @param productId2
	 * @param productType
	 * @param skuPics
	 * @param detailContentJson
	 * @param skuInput
	 * @param priceMarket
	 * @param priceSale
	 * @param stock:库存
	 * @param warehouseId:仓库
	 * @param groupIdList
	 *            :分组
	 * @return
	 */
	@Override
	public RtnInfo createProductSku(Long endMerchantUserId, Long productId1, Long productId2, Byte productType,
			List<ProductSkuPicInputBo> skuPics, String detailContentJson, ProductSkuInputBo skuInput,
			BigDecimal priceMarket, BigDecimal priceSale, Long stockNum, Long warehouseId, List<Long> groupIdList) {
		EndMerchantUserBo endMerchantUserBo = null;
		// 获取当前merchantId/shopId对应的商家用户
		ServiceReturnInfo merchantReturnInfo = endMerchantUserService.getEndMerchantUserById(endMerchantUserId);
		if (ServiceReturnUtils.isSuccess(merchantReturnInfo)) {
			if (merchantReturnInfo.getData() == null) {
				return ReturnUtils.error(ReturnCodes.MERCHANT_NOT_EXIST);
			} else {
				endMerchantUserBo = (EndMerchantUserBo) merchantReturnInfo.getData();
			}
		} else {
			return ReturnUtils.error(ReturnCodes.SYSTEM_EXCEPTION);
		}

		// 插入product库相关表.
		ServiceReturnInfo createProductSkuReturnInfo = productPublishService.createProductSku(endMerchantUserBo,
				productId1, productId2, productType, skuPics, detailContentJson, skuInput, priceMarket, priceSale,
				groupIdList);

		Long productSkuId = null;
		if (ServiceReturnUtils.isSuccess(createProductSkuReturnInfo)) {
			productSkuId = (Long) createProductSkuReturnInfo.getData();
		} else {
			return ReturnUtils.error(ReturnCodes.SYSTEM_EXCEPTION);
		}

		/**
		 * TODO 异常回滚操作pending. 插入user库库存表
		 */
		Long actualProductId;
		if (DbConstants.PRODUCT_TYPE_SERIAS_VIRTUAL == productType.byteValue()) {
			// 系列品
			actualProductId = productId2;
		} else {
			// 单品
			actualProductId = productId1;
		}
		ServiceReturnInfo createProductStockReturnInfo = productStockService.createProductStock(endMerchantUserBo,
				actualProductId, stockNum, warehouseId);
		if (ServiceReturnUtils.isSuccess(createProductStockReturnInfo)) {
			return ReturnUtils.success(productSkuId);
		} else {
			return ReturnUtils.error(ReturnCodes.SYSTEM_EXCEPTION);
		}

	}

}
